package httphandle

import (
	"emb/emb_server/util/dbutil"
	"emb/emb_server/util/handleutil"
	"fmt"
	"net/http"
)

type friengInfo struct {
	NickName string
	Icon     string
	Custom   string
}

// request : objectID  string
// respon : friengInfo
// { nickName string
// icon     string
// custom   string}
func getObjectData(w http.ResponseWriter, r *http.Request) {

	var httpCode = http.StatusOK
	var info = "success"
	var information interface{}

	fmt.Println("请求方IP地址：", r.RemoteAddr)
	defer func() {
		handleutil.SendMsg(w, httpCode, info, information)
	}()
	setHeader(w)
	err := r.ParseForm()
	if err != nil {
		httpCode = http.StatusBadRequest
		info = "参数解析失败！请使用x-www-form-urlencoded格式传输参数数据！"
		return
	}

	urlValue := r.Form["objectID"]
	fmt.Println("getObjectData:", urlValue)
	id := urlValue[0]

	info, information, ok := getDbData(id)
	if !ok {
		httpCode = http.StatusBadRequest
	}

}

//从数据库数据获取好友信息数据
func getDbData(id string) (string, interface{}, bool) {

	var nickName, icon, custom string
	var informationResult friengInfo
	info := "success"

	dbutil.InitDb()
	db := dbutil.GetDb()
	defer dbutil.CloseDb(db)

	sql := "select nickname,icon,custom from objects where id = $1"
	stmt, err := db.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		fmt.Println("From:getObjectData.Prepare---", err.Error())
		return info, nil, false
	}
	if id == "" {
		fmt.Println("From:getObjectData---- Id is null")
		info = "From:getObjectData---- Id is null"
		return info, nil, false
	}

	rows, err := stmt.Query(id)
	defer rows.Close()
	if err != nil {
		fmt.Println("From:getObjectData.Query---", err.Error())
		info = "From:getObjectData.Query---" + err.Error()
		return info, nil, false
	}

	if rows.Next() == false {
		fmt.Println("From:getObjectData---- find nothing")
		info = "From:getObjectData---- find nothing"
		return info, nil, false
	}

	err = rows.Scan(&nickName, &icon, &custom)
	if err != nil {
		fmt.Println("From:getObjectData.Scan---", err.Error())
		info = "From:getObjectData.Scan---" + err.Error()
		return info, nil, false
	}

	informationResult.NickName = nickName
	informationResult.Icon = icon
	informationResult.Custom = custom

	fmt.Println(informationResult)

	return info, informationResult, true

}
